package com.thread.lesson.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * @Author: Mr.Xi
 * @Description:
 * @Date: Create in 15:22 2021/6/30
 * @Modified By:
 */
//联系Thread ， 实现多线程同步下载图片
public class TestThread4 implements Runnable{
    private String url;
    private String name;

    public TestThread4(String url , String name){
        this.url = url;//网络图片地址
        this.name = name;//保存的文件名
    }

    /**
     * 下载网络图片的执行体
     */
    @Override
    public void run() {
        WebDownloader4 webDownloader = new WebDownloader4();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为："+name);
    }

    public static void main(String[] args) {
        TestThread4 t1 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fblog%2F201306%2F25%2F20130625150506_fiJ2r.jpeg&refer=http%3A%2F%2Fcdn.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1627632063&t=b8a518b16104b32e8666d80bca4409c4","1.jpg");
        TestThread4 t2 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fblog%2F201306%2F25%2F20130625150506_fiJ2r.jpeg&refer=http%3A%2F%2Fcdn.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1627632063&t=b8a518b16104b32e8666d80bca4409c4","2.jpg");
        TestThread4 t3 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fblog%2F201306%2F25%2F20130625150506_fiJ2r.jpeg&refer=http%3A%2F%2Fcdn.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1627632063&t=b8a518b16104b32e8666d80bca4409c4","3.jpg");

        //理想下载流程：先下载1，然后下载2，最后下载3
        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
        //正确结果：每次下载顺序不确定
    }

}

/**
 * 下载器
 */
class WebDownloader4{
    //下载方法
    public void downloader(String url , String name){
        //下载方法
        try {
            FileUtils.copyURLToFile(new URL(url) , new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
        }
    }
}